<template lang="pug">
mt-dialog(
v-model="appmodel"
cancel-text="取消"
title="批次列表"
:on-close="updateModel"
:on-cancel="updateModel"
hide-confirm
size="large"
)
  data-page(
        v-bind="pageParams"
      )
    span(style="color: rgb(53, 160, 0);margin-bottom: 15px;position: absolute;top: 120px;") 处理批次号 {{ props.batchNumber }}
    mt-table(
      v-bind="tableProps"
    )
processing(v-model="processShow" :selectionRow="selectionRow" :batchNumber="props.batchNumber" @message-to-parent="messageToParent")
sampleTrajectory(v-model="trajectoryShow" :selectionRow="specimenRow")  
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type TableProps,
  useNotify,
  type Action,
} from "@scmt/common-components";
import {
  type ApiBasedOptions,
  type QueryPagination,
  useApi,
} from "@scmt/core-api";
import { type SpecimenQueryParams } from "@scmt/api-lis-specimen";
import processing from "./processing.vue";
import sampleTrajectory from "../components/sampleTrajectory.vue";
import { useRequest } from "@scmt/common-hooks";
const $api = useApi();
const $notify = useNotify();
const $utils = useUtils();
const queryPramas = reactive<SpecimenQueryParams>({
  startDate: $utils.date().startOf("date").format("YYYY-MM-DD HH:mm:ss"),
  endDate: $utils.date().endOf("date").format("YYYY-MM-DD HH:mm:ss"),
  pageNum: 1,
  pageSize: 20,
});
const processShow = ref(false);

const appmodel = defineModel({
  default: false,
});

const emit = defineEmits(["message-to-parent"]);
const trajectoryShow = ref(false);
const specimenRow = ref({});

const selectionRow = ref([]);
import { useUtils } from "@scmt/lib-utils";
import { type PatientEntity } from "@scmt/api-patient";
import { ESpeimenTableColumnKey, specimenColumns } from "@scmt/api-common";
const patients = ref<ApiBasedOptions<PatientEntity>>([]);

const updateModel = () => {
  appmodel.value = false;
  request("tableData");
};

const messageToParent = () => {
  appmodel.value = false;
  emit("message-to-parent");
};

//添加 Props属性
const props = defineProps({
  batchNumber: {
    type: String,
    default: "",
  },
  state: {
    type: Number,
    default: null,
  },
});

const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    const params = Object.assign({}, queryPramas, q);
    return $api.lis.specimen.getSpecimenPageList(params);
  },
  listDoctorAsOptions: (val: string) =>
    $api.user.listDoctorAsOptions({ officeId: val }),
  batchGenerateBarcode: (q: any) => {
    return $api.lis.specimen.batchGenerateBarcode(q).then(() => {
      $notify.success("生成条码成功");
      request("tableData");
    });
  },
  listAsOptions: () => {
    return $api.lis.specimen.category.listAsOptions();
  },
  patients: async (keyword: string) => {
    if (!keyword && patients.value.length) {
      return patients.value;
    }

    return $api.patient.listAsOptions({ keyword });
  },
  loadcollectionMethod: () => $api.dict.item.listAsOptions("collection_method"),
});

onMounted(() => {
  request("listDoctorAsOptions");
  request("listAsOptions");
  request("loadcollectionMethod");
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "outpatientNumber",
      label: "业务编号",
    },
    {
      prop: "patientName",
      label: "患者姓名",
    },
    {
      prop: "barcode",
      label: "标本条码",
    },
    {
      prop: "billingDepartment",
      label: "开单科室",
      as: "select",
      options: {
        render: "office-table",
        loadMethod: $api.upms.org.listAsOptions,
      },
    },

    {
      prop: "billingTime",
      label: "开单时间",
      as: "date",
    },
    {
      prop: "specimenTypeId",
      label: "标本类型",
      as: "select",
      options: {
        loadMethod: () => {
          return $api.lis.specimen.category.listAsOptions();
        },
      },
    },
  ];

  const headerActions: Action[] = [
    {
      label: "标本处理",
      event: "generateSignature",
      type: "primary",
      disabled: selectionRow?.value?.length == 0,
      visible: props.state == 5,
    },
  ].filter((i) => i.visible === void 0 || i.visible);
  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    onQuery: () => request("tableData", { batchNumber: props.batchNumber }),
    onAct: onPageActions,
    actions: headerActions,
    columns: 4,
    flex: true,
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    insertIndex: false,
    columns: [
      {
        type: "selection",
        label: "序号",
        width: "60px",
      },
      specimenColumns[ESpeimenTableColumnKey.Source],
      specimenColumns[ESpeimenTableColumnKey.OutpatientNumber],
      specimenColumns[ESpeimenTableColumnKey.Barcode],
      specimenColumns[ESpeimenTableColumnKey.PatientName],
      specimenColumns[ESpeimenTableColumnKey.Sex],
      specimenColumns[ESpeimenTableColumnKey.Age],
      specimenColumns[ESpeimenTableColumnKey.State],
      specimenColumns[ESpeimenTableColumnKey.SpecimenTypeId],
      {
        prop: "sampleContainer",
        tooltip: true,
        label: "试管名称",
        width: "150px",
        render: ({ row }) => {
          let resText = row.sampleContainer + "";
          return h(
            "div",
            {
              style: {
                width: "100%",
                background: row.sampleContainerColor,
              },
            },
            resText
          );
        },
      },
      {
        prop: "specs",
        tooltip: true,
        label: "规格",
        minWidth: 120,
      },
      {
        prop: "additive",
        label: "添加剂",
      },
      {
        prop: "collectionMethod",
        label: "采集方式",
        minWidth: 150,
        render: ({ row }) => {
          const patientType = data.loadcollectionMethod ?? [];
          let resText = row.collectionMethod;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.collectionMethod
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "bloodCollectionVolume",
        label: "采血量",
      },
      specimenColumns[ESpeimenTableColumnKey.ApplicationProject],
      specimenColumns[ESpeimenTableColumnKey.BillingDepartment],
      specimenColumns[ESpeimenTableColumnKey.BillingDoctor],
      specimenColumns[ESpeimenTableColumnKey.BillingTime],
      {
        prop: "collectionId",
        label: "采集医生",
        render: ({ row }) => {
          const patientType = data.listDoctorAsOptions ?? [];
          let resText = row.collectionId;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.collectionId
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "collectionTime",
        label: "采集时间",
        format: "datetime",
      },
      {
        prop: "sendInspectionId",
        label: "送检医生",
        render: ({ row }) => {
          const patientType = data.listDoctorAsOptions ?? [];
          let resText = row.sendInspectionId;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.sendInspectionId
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "sendInspectionTime",
        label: "送检时间",
        format: "datetime",
      },
      {
        prop: "signee",
        label: "签收人",
        render: ({ row }) => {
          const patientType = data.listDoctorAsOptions ?? [];
          let resText = row.signee;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter((item) => item.value == row.signee);
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        label: "操作",
        fixed: "right",
        actions: [
          {
            label: "标本轨迹",
            event: "check",
            type: "primary",
          },
        ],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),

    onSelectionChange: (selection: any) => {
      selectionRow.value = selection;
    },
    highlightCurrentRow: true,
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "generateSignature":
      processShow.value = true;
      break;
    case "check":
      specimenRow.value = model;
      trajectoryShow.value = true;
      break;
  }
};

watch(
  appmodel,
  (visible: boolean) => {
    if (visible) {
      queryPramas.patientName = "";
      queryPramas.outpatientNumber = "";
      queryPramas.barcode = "";
      queryPramas.billingDepartment = "";
      queryPramas.billingTime = "";
      queryPramas.specimenTypeId = "";
      request("tableData", {
        processBatchNumber: props.batchNumber,
      });
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped></style>
